package org.jsola.hr.common;

import lombok.extern.slf4j.Slf4j;
import org.jsola.common.FileKit;
import org.jsola.exception.ParamException;
import org.springframework.util.ObjectUtils;

import javax.imageio.ImageIO;
import javax.net.ssl.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

@Slf4j
public class FileDown {

    /**
     * 下载文件到本地(支持http和https)
     *
     * @param netUrl 网络图片地址
     * @return 本地地址
     */
    public static String getFilePath(String netUrl) {
        //判断http和https
        File file = null;
        if (netUrl.startsWith("https://")) {
            file = getNetUrlHttps(netUrl);
        } else {
            file = getNetUrlHttp(netUrl);
        }
        return file.getAbsolutePath();
    }

    /**
     * 下载文件到本地(支持http和https)
     *
     * @param netUrl 网络图片地址
     * @return 本地地址
     */
    public static File getFile(String netUrl) {
        //判断http和https
        File file = null;
        if (netUrl.startsWith("https://")) {
            file = getNetUrlHttps(netUrl);
        } else {
            file = getNetUrlHttp(netUrl);
        }
        return file;
    }

    /**
     * 下载文件到本地(支持http)
     *
     * @param netUrl 远程地址
     * @throws Exception
     */
    public static File getNetUrlHttp(String netUrl) {
        //对本地文件命名
        File file = null;

        int index = netUrl.lastIndexOf(".");
        String geshi = netUrl.substring(index + 1);

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            String systemTempPath = FileKit.getSystemTempPath();
            String fileName = "idCard." + geshi;
            new File(systemTempPath).mkdir();
            file = new File(systemTempPath, fileName);
            //下载
            urlfile = new URL(netUrl);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            log.error("远程图片获取错误：" + netUrl);
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return file;
    }

    /**
     * 下载文件到本地(支持https)
     *
     * @param fileUrl 远程地址
     * @throws Exception
     */
    public static File getNetUrlHttps(String fileUrl) {
        //对本地文件进行命名
        File file = null;

        int index = fileUrl.lastIndexOf(".");
        String geshi = fileUrl.substring(index + 1);

        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            String systemTempPath = FileKit.getSystemTempPath();
            String fileName = "idCard." + geshi;
            new File(systemTempPath).mkdir();
            file = new File(systemTempPath, fileName);

            System.out.println(file.getPath());
            SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
            sslcontext.init(null, new TrustManager[]{new X509TrustUtiil()}, new java.security.SecureRandom());
            URL url = new URL(fileUrl);
            HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslsession) {
                    log.warn("WARNING: Hostname is not matched for cert.");
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
            HttpsURLConnection urlCon = (HttpsURLConnection) url.openConnection();
            urlCon.setConnectTimeout(6000);
            urlCon.setReadTimeout(6000);
            int code = urlCon.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                throw new Exception("文件读取失败");
            }
            // 读文件流
            in = new DataInputStream(urlCon.getInputStream());
            out = new DataOutputStream(new FileOutputStream(file));
            byte[] buffer = new byte[2048];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            log.error("远程图片获取错误：" + fileUrl);
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
                if (null != in) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return file;
    }

    /**
     * 压缩图片(第三个参数没用,我也不知道能给你压缩到几兆,反正能变小就对了)
     *
     * @param image     图片文件
     * @param threshold 图片大小阈值,大于这个值我才给你压缩
     * @param targetM   具体想要压缩到几兆
     * @return 压缩后的文件
     */
    public static File resizeImage(File image, int targetM, int threshold) {
        if (ObjectUtils.isEmpty(image)) {
            throw new ParamException("图片为空");
        }
        long fileSizeInBytes = image.length();
        long fileSizeInM = fileSizeInBytes / 1024 / 1024;
        if (fileSizeInM < threshold) {
            return image;
        }
        Image srcImg = null;
        try {
            srcImg = ImageIO.read(image);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String absolutePathFile = image.getAbsolutePath();
        String absolutePath = absolutePathFile.substring(0, absolutePathFile.lastIndexOf(File.separatorChar));
        String newFilePath = absolutePath + File.separatorChar + UUID.randomUUID();
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert bi != null;
        float width = bi.getWidth();
        float height = bi.getHeight();
        float newWidth = targetM * width / fileSizeInM;
        float newHeight = targetM * height / fileSizeInM;
        BufferedImage buffImg = null;
        buffImg = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
        //使用TYPE_INT_RGB修改的图片会变色
        buffImg.getGraphics().drawImage(
                srcImg.getScaledInstance((int) newWidth, (int) newHeight, Image.SCALE_SMOOTH), 0,
                0, null);
        File resultFile = new File(newFilePath);
        try {
            ImageIO.write(buffImg, "JPEG", resultFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultFile;
    }

    public static void main(String[] args) {
        File file = new File("D:\\file\\20220412_093744(1).jpg");
        resizeImage(file, 8, 9);

    }

}